package com.ec.vs.controller;

import com.ec.common.domain.Result;
import com.ec.vs.entity.VsAppointment;
import com.ec.vs.service.VsService;
import com.ec.vs.vo.VsAppointmentVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

@Api(tags = "用户预约管理")
@RestController
@RequestMapping("/visit/user/reservations")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final VsService vsService;

    /**
     * 提交预约（用户端）
     */
    @ApiOperation("提交预约")
    @PostMapping("/visits")
    public Result<String> submitVisitAppointment(@Valid @RequestBody VsAppointmentVo dto) {
        try {
            log.info("用户提交预约, dto={}", dto);

            // 校验老人ID是否必填
            if (dto.getType() == 0 && dto.getElderId() == null) {
                return Result.error("探访预约时，老人ID不能为空");
            }

            // 检查时间冲突
            if (vsService.checkTimeConflict(dto)) {
                return Result.error("该日期的预约数量已达到上限，请选择其他日期");
            }

            // 检查用户在一天内提交的预约总数是否超过 2 次
            if (vsService.checkUserDailyLimit(dto)) {
                return Result.error("您一天内只能提交两次预约，请选择其他日期");
            }

            // 检查用户是否已经在同一时间提交了不同类型的预约
            if (vsService.checkUserTimeConflict(dto)) {
                return Result.error("您已经在同一时间提交了不同类型的预约，请选择其他时间");
            }

            // VO → Entity
            VsAppointment appointment = new VsAppointment();
            BeanUtils.copyProperties(dto, appointment);

            int result = vsService.saveVisitAppointment(appointment);
            if (result > 0) {
                return Result.ok("预约提交成功");
            } else {
                return Result.error("预约提交失败");
            }
        } catch (Exception e) {
            log.error("用户提交预约失败", e);
            return Result.error("预约提交失败");
        }
    }

    /**
     * 根据 userId 查看预约信息
     */
    @ApiOperation("查看预约信息")
    @GetMapping("/visits/{userId}")
    public Result<VsAppointment> getVisitAppointmentStatus(@PathVariable Long userId) {
        try {
            log.info("用户查询预约, userId={}", userId);
            VsAppointment appointment = vsService.findVisitAppointmentByUserId(userId);
            if (appointment != null) {
                return Result.ok(appointment);
            } else {
                return Result.error("未找到该预约信息");
            }
        } catch (Exception e) {
            log.error("用户查询预约失败", e);
            return Result.error("查询预约信息失败");
        }
    }

    /**
     * 用户端：多条件分页查询自己的预约记录
     * 支持姓名、手机号、老人姓名、预约状态单独或任意组合查询
     */
    @ApiOperation("查询我的预约记录（支持组合条件）")
    @GetMapping("/visits/search")
    public Result<Object> searchMyAppointments(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String mobile,
            @RequestParam(required = false) String elderName,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        // 复用 service 层已实现的通用查询
        return vsService.searchVisitAppointments(name, mobile, elderName, status, page, size);
    }

    /**
     * 用户端：直接取消正在审核（待确定）的预约
     * 只允许取消 status = 0 的记录
     */
    @ApiOperation("取消待审核的预约")
    @PostMapping("/visits/{id}/cancel")
    public Result<String> cancelMyAppointment(@PathVariable Long id) {
        try {
            log.info("用户取消预约, id={}", id);
            int rows = vsService.cancelVisitAppointment(id);
            if (rows > 0) {
                return Result.ok("取消成功");
            } else {
                return Result.error("取消失败，请确认预约状态是否为“待确定”");
            }
        } catch (Exception e) {
            log.error("用户取消预约失败", e);
            return Result.error("取消预约失败");
        }
    }
}